<template>
  <view class="flex flex-col min-h-screen bg-[#f5f5f5] p-4">
    <!-- HTML输入框 -->
    <nut-textarea
      v-model="htmlCode"
      placeholder="请输入HTML代码"
      class="mb-4 bg-white rounded-xl shadow p-2 text-[28rpx]"
      rows="8"
    />
    <!-- 预览按钮 -->
    <nut-button type="primary" class="mb-4" @click="showPreview = true">预览</nut-button>

    <!-- 预览区 -->
    <view v-if="showPreview" ref="previewRef" class="bg-white rounded-xl shadow p-4 mb-4 min-h-[200rpx] overflow-x-auto">
      <view v-html="htmlCode"></view>
    </view>

    <view class="flex-1" />
    <!-- 截图按钮 -->
    <nut-button type="success" class="w-full mt-8" @click="handleScreenshot">截图并下载</nut-button>
  </view>
</template>

<script setup>
import { ref } from 'vue';
// import { showToast } from '@nutui/nutui-taro';
// @ts-ignore
import html2canvas from 'html2canvas';


const htmlCode = ref('<h1 style="color:#165DFF;">Hello World</h1>');

const showPreview = ref(false);

const previewRef = ref(null);

/**
 * 截图并下载当前预览区
 * 性能优化：只截取预览区，避免全页面大图，提升速度
 */
const handleScreenshot = async () => {
  if (!showPreview.value || !previewRef.value) {
    // showToast.text('请先预览HTML内容');
    return;
  }
  try {
    const canvas = await html2canvas(previewRef.value, { useCORS: true });
    const url = canvas.toDataURL('image/png');
    // 创建下载链接
    const a = document.createElement('a');
    a.href = url;
    a.download = 'preview.png';
    a.click();
    // showToast.success('截图已保存');
  } catch (e) {
    // showToast.fail('截图失败');
  }
};
</script>